from framework_strategy.gopy.driver.core import OPRedis, RedisMixnis
from framework_strategy.gopy.gateways.settings import REDISSETTING


# Exchange cache data class
#   define cache source
class CacheData(object):

    def __init__(self, db_name) -> None:
        self.cache = RedisMixnis.init(
            db=REDISSETTING.DB_CONF.get(db_name), port=7006)
        self.key = '%s:%s:%s'


# # Method class
#   get and parse data
class TickerCacheMeta(CacheData):

    def __init__(self) -> None:
        super().__init__(db_name='ticker')

    def _get(self, exchange, market):
        key = self.key % (exchange, market, REDISSETTING.TICKER_KEY_CONF.get(exchange))
        data = self.cache.operator(method='get', name=key)
        data = self.cache.byte2dict(data)
        if exchange == 'ftx':
            data = {"success": True, 'result': data}
        return data


class TradeCacheMeta(CacheData):

    def __init__(self) -> None:
        super().__init__(db_name='trade')

    def _get(self, exchange, market, start=0, end=-1):
        key = self.key % (exchange, market, REDISSETTING.TRADE_KEY_CONF.get(exchange))
        data = self.cache.operator(
            method='lrange',
            name=key,
            start=start, end=end)
        data = self.cache.byte2dict(data)
        if exchange == 'ftx':
            data = {"success": True, 'result': data}
        return data


class DepthCacheMeta(CacheData):

    def __init__(self) -> None:
        super().__init__(db_name='depth')

    def _get(self, exchange, market):
        key = self.key % (exchange, market, REDISSETTING.DEPTH_KEY_CONF.get(exchange))
        data = self.cache.operator(method='get', name=key)
        data = self.cache.byte2dict(data)
        if exchange == 'ftx':
            data = {"success": True, 'result': data}
        return data


# Interface class
class InterfaceCacheData(object):

    def __init__(self) -> None:
        self.ticker = TickerCacheMeta()
        self.depth = DepthCacheMeta()
        self.trade = TradeCacheMeta()

    def get(self, exchange, method, market, **kwargs):
        return getattr(self, method)._get(exchange, market, **kwargs)


ICD = InterfaceCacheData()

